"""This module contains utilities to manage image and audio resources"""
import pygame, sys, os
from pygame.locals import *

_img_cache = {}
_snd_cache = {}
_img_dir = 'data/img'.split('/')
_snd_dir = 'data/sound'.split('/')

def set_images_directory(images_directory):
    """set default image directory / separated, for example 'data/img'"""
    global _img_dir
    _img_dir = images_directory.split('/')
def set_sounds_directory(sounds_directory):
    """set default sounds directory / separated, for example 'data/sounds'"""
    global _snd_dir
    _snd_dir = sounds_directory.split('/')

def load_sound(filename):
    """Loads a sound file and stores it in the cache
    filename: '/' separated path within the images directory, for example:
            'sfx/bang.wav' for an sound in data/sounds/sfx/bang.wav"""
    pass
    
def load_image(filename, colorkey=None, bit_alpha = 0):
    """Loads an image and stores it on the chache
    filename: '/' separated path within the images directory, for example:
            'characters/player.png' for an image in data/images/characters/player.png
    colorkey: optional: can be -1 for using the top-left corner pixel color or a given color
    exists on load error.
    """
    rtimg = None
    if _img_cache.has_key(filename): # if is in the cache, return it
        rtimg = _img_cache[filename]
    else:
        fullpath = _img_dir + filename.split('/')
        try:
            rtimg = pygame.image.load(os.path.join(*(fullpath))) # TODO os.path.join with lists
        except pygame.error, message:
            print '[resource_manager]Could not load specified file:', '/'.join(fullpath)
            raise SystemExit, message
        try:
            rtimg = rtimg.convert_alpha() # keep transparency
        except pygame.error, message:
            pass
            
        _img_cache[filename] = rtimg.copy()
    if colorkey is not None: # set the colorkey for alpha masked images
        if colorkey is -1:
            colorkey = rtimg.get_at((0,0))
            
        rtimg.set_colorkey(colorkey, RLEACCEL)
    
    return rtimg
